//
//  ClubStrategyListViewController.swift
//  ClubanGame
//
//  Created by Apple on 2024/8/13.
//  Copyright © 2024 94Wan. All rights reserved.
//

import UIKit
import JXSegmentedView

private let headerID    = "ClubStrategyHeaderView"

class ClubStrategyListViewController: ClubBaseViewController {

    private var topView = ClubStrategyListTopView()
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.register(ClubStrategyListView.self, ClubStrategyHistoryCell.self)
        tableView.register(ClubStrategyTitleHeaderView.self, forHeaderFooterViewReuseIdentifier: headerID)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        tableView.rowHeight = 80.0.Scale
        tableView.sectionHeaderHeight = 42.0.Scale
        tableView.sectionFooterHeight = 0
        tableView.contentInset = UIEdgeInsets.zero
        tableView.sectionHeaderTopPadding = 0
        return tableView
    }()
    
    private var pageIndex = 1
    private var bbs_num = 0
    
    private var moreView = ClubJoinedStrategyView()

    private var attentionModels:[ClubGameCommunityAllListModel] = [] {
        didSet{
            if self.attentionModels.count > 0 {
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
                    self.topView.heightConstraint?.constant = 82.0.Scale
                    self.tableView.topConstraint?.constant = 85.0.Scale
                }
            }else{
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
                    self.topView.heightConstraint?.constant = 0
                    self.tableView.topConstraint?.constant = 0
                }
            }
        }
    }
    
    private var sourceData: [ClubSquareModel] = []
//    private var bbsModels:[ClubGameCommunityAllListModel] = []
//    private var historyModels:[ClubGameCommunityAllListModel] = []
//    private var models:[ClubGameCommunityAllListModel] = []
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        loadData()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white
        
        view.subviews{
            topView
            tableView
        }
        
        if #available(iOS 15.0, *) {
            self.tableView.sectionHeaderTopPadding = 0
        } else {
            // Fallback on earlier versions
        }

        topView.leading(0).trailing(0).top(0).height(82.0.Scale)
        tableView.leading(0).trailing(0).bottom(0).top(85.0.Scale)

        moreView.frame = CGRect(x: 0, y: 0, width: .screenWidth, height: .screenHeight)
        UIApplication.window?.addSubview(moreView)
        moreView.isHidden = true
        
        tableView.refresh_loadMore {
            self.loadMoreData()
        }.refresh_pull {
            self.loadNewData()
        }
        
        topView.toStrategyDetailVC = { md in
            self.toDetailVC(md: md)
        }
        topView.moreBlock = { dataArr in
            var tempArray = dataArr
            tempArray.remove(at: 0)
            var md = ClubGameCommunityAllListModel()
            md.isLocal = true
            md.icon = "Square_forum_add"
            md.name = "添加"
            md.id = "001000"
            tempArray.insert(md, at: dataArr.count - 1)
            self.moreView.sourceData = tempArray
            self.moreView.isHidden = false
        }
        
        moreView.removeView = {
            self.moreView.isHidden = true
        }
        
        moreView.toStrategyDetailVC = { model in
            self.moreView.isHidden = true
            if model.id == "001000" {
                let moreVC = ClubJoinedMoreStrategyVC()
                moreVC.is_bbs = ""
                moreVC.joinedStrategy = { md in
                    self.attentionModels.append(md)
                    self.topView.sourceData = self.attentionModels
                }
                self.navigationController?.pushViewController(moreVC, animated: true)
            }else{
                
                self.toDetailVC(md: model)
            }
        }
    }
    
}

//MARK: - UITableViewDelegate, UITableViewDataSource
extension ClubStrategyListViewController: UITableViewDelegate, UITableViewDataSource {

    func numberOfSections(in tableView: UITableView) -> Int {
        return sourceData.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        let model = sourceData[section]
        if model.title == "最近浏览" {
            return 1
        }else{
            return model.data.count
        }        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let sectionM = sourceData[indexPath.section]
        if sectionM.title == "最近浏览" {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ClubStrategyHistoryCell", for: indexPath) as! ClubStrategyHistoryCell
            cell.models = sectionM.data
            cell.toDetailStrategyVC = { md in
                self.toDetailVC(md: md)
            }
            return cell
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "ClubStrategyListView", for: indexPath) as! ClubStrategyListView
            cell.model = sectionM.data[indexPath.row]
            cell.joinStrategy = { md in
                if let index = self.attentionModels.firstIndex(where: { $0.id == md.id }) {
                    self.attentionModels.remove(at: index)
                }else{
                    self.attentionModels.append(md)
                }
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                    self.topView.sourceData = self.attentionModels
                }
            }
            cell.todDetailVC = { md in
                self.toDetailVC(md: md)
            }
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let sectionM = sourceData[indexPath.section]
        if sectionM.title != "最近浏览" {
            let md = sectionM.data[indexPath.row]
            self.toDetailVC(md: md)
        }
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let sectionM = sourceData[section]
        let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: headerID) as! ClubStrategyTitleHeaderView
        header.titleString = sectionM.title
        if sectionM.title == "其他论坛" && self.bbs_num > 4 {
            header.isShowMore = true
        }
        header.moreBlock = {
            let moreVC = ClubJoinedMoreStrategyVC()
            moreVC.is_bbs = "1"
            moreVC.joinedStrategy = { md in
                self.attentionModels.append(md)
                self.topView.sourceData = self.attentionModels
            }
            self.navigationController?.pushViewController(moreVC, animated: true)
        }
        return header
    }
    
    private func toDetailVC(md: ClubGameCommunityAllListModel){
        
        if var localData: [ClubGameCommunityAllListModel] = UserDefaultsManager.getModelsData(forKey: .browseHistory) {
            if !localData.contains(where: { $0.id == md.id }) {
                localData.append(md)
                UserDefaultsManager.setModelsData(localData, forKey: .browseHistory)
            }
        }else{
            UserDefaultsManager.setModelsData([md], forKey: .browseHistory)
        }
        
        if md.is_bbs == 1 {
            let community = ClubSquareDatailViewController()
            community.communityId = md.id
            self.navigationController?.pushViewController(community, animated: true)
        }else{            
            let community = ClubGameDetailViewController()
            community.gameId = md.id
            community.toForum = true
            self.navigationController?.pushViewController(community, animated: true)
        }
        
        
    }
}

//MARK: data
extension ClubStrategyListViewController {
    
    func loadData() -> Void {
//        ToastUtil.show()
        
        Task {
            var user_id = ""
            if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                user_id = uid
            }
            let res = await self.network.requestMoreData(.communityList(page: pageIndex, type: "", keyword: "", uid: user_id, is_bbs: ""),type: ClubGameSquareListModel.self)
            ToastUtil.dismiss()
            tableView.refresh_end()
            if res.isSuccess, let model = res.model {
                self.bbs_num = model.bbs_num
                self.sourceData.removeAll()
                if let data = model.data{
                    let md = ClubSquareModel(title: "推荐游戏论坛", data: data)
                    self.sourceData.append(md)
                }
                if let bbs = model.bbs{
                    let md = ClubSquareModel(title: "其他论坛", data: bbs)
                    self.sourceData.append(md)
                }
                self.loadLocalData()
            }
        }
        self.loadTopData()
    }
    
    private func loadLocalData(){
        
        if let localData: [ClubGameCommunityAllListModel] = UserDefaultsManager.getModelsData(forKey: .browseHistory) {
            let md = ClubSquareModel(title: "最近浏览", data: localData)
            sourceData = replaceOrAddTitleInArray(sourceData, targetTitle: "最近浏览", newModel: md)
        }

        let temp = sortClubSquareModels(sourceData)
        sourceData = temp
        self.tableView.reloadData()
    }
    
    private func replaceOrAddTitleInArray(
        _ array: [ClubSquareModel],
        targetTitle: String,
        newModel: ClubSquareModel
    ) -> [ClubSquareModel] {
        // 检查数组中是否存在目标 title
        var modifiedArray = array
        if let index = modifiedArray.firstIndex(where: { $0.title == targetTitle }) {
            // 如果找到目标 title，替换对应元素
            modifiedArray[index] = newModel
        } else {
            // 如果未找到目标 title，添加新元素
            modifiedArray.append(newModel)
        }
        return modifiedArray
    }


    
    private func sortClubSquareModels(_ array: [ClubSquareModel]) -> [ClubSquareModel] {
        // 定义排序规则
        let priorityOrder: [String: Int] = [
            "其他论坛": 0,
            "最近浏览": 1,
            "推荐游戏论坛": 2
        ]
        
        // 对数组进行排序
        let sortedArray = array.sorted { model1, model2 in
            let priority1 = priorityOrder[model1.title] ?? Int.max // 未知标题优先级最大
            let priority2 = priorityOrder[model2.title] ?? Int.max
            return priority1 < priority2
        }
        
        // 移除重复元素
        var seenTitles = Set<String>()
        let uniqueArray = sortedArray.filter { model in
            if seenTitles.contains(model.title) {
                return false
            } else {
                seenTitles.insert(model.title)
                return true
            }
        }
        
        return uniqueArray
    }
    
    func loadTopData(){
        
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
             
            Task {
                let res = await self.network.request(.followCommunityList(uid: uid),type: ClubGameCommunityAllListModel.self)
                if res.isSuccess, let models = res.models {
                    self.attentionModels = models
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
                        self.topView.sourceData = self.attentionModels
                    }
                }
            }
        } else {
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
                self.topView.heightConstraint?.constant = 0
                self.tableView.topConstraint?.constant = 0
            }
        }
        
    }

    @objc func loadNewData() -> () {
        pageIndex = 1
        loadData()
    }
    
    @objc func loadMoreData() -> () {

        pageIndex += 1
        Task {
            var user_id = ""
            if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                user_id = uid
            }
            let res = await self.network.requestMoreData(.communityList(page: pageIndex, type: "", keyword: "", uid: user_id, is_bbs: ""),type: ClubGameSquareListModel.self)
            tableView.refresh_end()
            if res.isSuccess, let models = res.model?.data {
//                self.models.append(contentsOf: models)
                self.addElementsIfTitleMatches(models, matchingTitle: "推荐游戏论坛")
                self.tableView.reloadData()
            }
        }
    }
    
    private func addElementsIfTitleMatches(_ newElements: [ClubGameCommunityAllListModel], matchingTitle: String) {
        
        var tempData = sourceData
        // 遍历数组并修改
        if let index = tempData.firstIndex(where: { $0.title == matchingTitle }) {
            tempData[index].data.append(contentsOf: newElements)
        }
        sourceData = tempData
    }
}

extension ClubStrategyListViewController:JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}


struct ClubSquareModel: Convertible  {

    var title: String     = ""
    var data: [ClubGameCommunityAllListModel] = []
}
